package io.zerous.zexgraph;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    LuaMachine luaMachine;

    PlotView plotView;

    DrawerLayout drawerLayout;
    ActionBarDrawerToggle actionBarDrawerToggle;
    ActionBar actionBar;

    private String currentScriptName = "";

    float pixelPerUnit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        actionBar = getSupportActionBar();

        drawerLayout = findViewById(R.id.mainDrawer);

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.manage_plots, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                actionBar.setTitle(R.string.manage_plots);
                Toast.makeText(MainActivity.this, "还没做完...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                actionBar.setTitle(R.string.app_name);
            }
        };

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        plotView = findViewById(R.id.mainPlotView);
        luaMachine = new LuaMachine();

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();


        String theFile = getIntent().getStringExtra("cFileName") != null ? getIntent().getStringExtra("cFileName") : "";

        if (!theFile.isEmpty() && !"null".equals(theFile)) {
            currentScriptName = theFile;

            luaMachine.loadScript(FileUtils.readTextFile(MainActivity.this, currentScriptName));

            plotView.setPlot(new PlotView.Plot() {
                @Override
                public float drawPlot(float x) {
                    return luaMachine.runScript(x);
                }
            });

            plotView.reset();

            if (getSupportActionBar() != null) getSupportActionBar().setSubtitle(currentScriptName);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onRunScript(MenuItem item) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(R.string.select_file);
        final ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, FileUtils.getSrcFileNames(this));
        b.setAdapter(listAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                currentScriptName = (String)listAdapter.getItem(which);

                luaMachine.loadScript(FileUtils.readTextFile(MainActivity.this, currentScriptName));

                plotView.setPlot(new PlotView.Plot() {
                    @Override
                    public float drawPlot(float x) {
                        return luaMachine.runScript(x);
                    }
                });

                plotView.reset();

                if (getSupportActionBar() != null)
                    getSupportActionBar().setSubtitle(currentScriptName);
            }
        });
        b.show();
    }

    public void onEditItem(MenuItem item) {
        Intent intent = new Intent(MainActivity.this, EditorActivity.class);
        intent.putExtra("cFileName", currentScriptName);
        startActivity(intent);
    }

    public void setPlotUnitSize(MenuItem item) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        final EditText inputSize = new EditText(this);
        b.setView(inputSize);
        b.setTitle(R.string.set_plot_pixel_per_unit);
        b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String sizeStr = inputSize.getEditableText().toString();
                boolean pass = true;
                for (int i = 0;i < sizeStr.length();++i) {
                    char index = sizeStr.charAt(i);
                    if (!(Character.isDigit(index) || index == '.')) {
                        pass = false;
                    }
                }

                if (pass) {
                    pixelPerUnit = Float.parseFloat(sizeStr);

                    plotView.setPixelPerUnit(pixelPerUnit);
                } else {
                    Toast.makeText(MainActivity.this, "必须要输入数字...（终于把这bug修了）", Toast.LENGTH_SHORT).show();
                }
            }
        });
        b.show();


        //plotView.setPixelPerUnit(pixelPerUnit);
    }

    public void onAboutDialog(MenuItem menuItem) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(R.string.about_dialog);
        b.setMessage("项目地址: https://gitee.com/Zerous/ZexGraph \n 高中学渣用课余时间写的小程序。代码很乱，欢迎各个大佬前来批评~\n作者:ZerAx");
        AlertDialog a = b.create();
        a.show();
        TextView tv = a.findViewById(android.R.id.message);
        if (tv != null) Linkify.addLinks(tv, Linkify.WEB_URLS);
    }
}
